#include <stdio.h>
#include <stddef.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>

#define BUF_SIZE 1024

int main (int argc, char **argv)
{
    if (argc != 3) {
        fprintf(stderr, "Usage: %s <cmdline file> <argument name>\n", (argc > 0 ? argv[0] : NULL));
        return 1;
    }
    
    FILE *f = fopen(argv[1], "r");
    if (!f) {
        fprintf(stderr, "Failed to open file.");
        return 1;
    }
    
    char buf[BUF_SIZE];
    int buf_start = 0;
    int buf_used = 0;
    
    void handle_option (char *name, int name_len, char *data, int data_len)
    {
        if (!strcmp(name, argv[2])) {
            if (data_len < 0) {
                printf("\n");
            } else {
                printf("%s\n", data);
            }
            exit(0);
        }
    }
    
    void parse_buffer (int final)
    {
        while (buf_used > 0) {
            // treat spaces and newlines as option separators
            int i;
            for (i = 0; i < buf_used;) {
                if (buf[buf_start + i] == ' ' || buf[buf_start + i] == '\n') {
                    if (i == 0) {
                        buf_start++;
                        buf_used--;
                        continue;
                    } else {
                        break;
                    }
                }
                i++;
            }
            
            if (i == buf_used && (!final || i == 0)) {
                return;
            }
            
            // copy option to buffer
            char optbuf[i + 1];
            memcpy(optbuf, buf + buf_start, i);
            optbuf[i] = '\0';
            
            // look for '='
            int j;
            for (j = 0; j < i; j++) {
                if (optbuf[j] == '=') {
                    optbuf[j] = '\0';
                    handle_option(optbuf, j, optbuf + (j + 1),  i - j - 1);
                    break;
                }
            }
            if (j == i) {
                handle_option(optbuf, i, NULL, -1);
            }
            
            // update buffer
            buf_start += i;
            buf_used -= i;
        }
    }
    
    while (1) {
        // read data
        int avail = BUF_SIZE - (buf_start + buf_used);
        if (avail == 0) {
            fprintf(stderr, "Out of buffer.");
            return 1;
        }
        int bytes = fread(buf + (buf_start + buf_used), 1, avail, f);
        if (bytes <= 0) {
            break;
        }
        buf_used += bytes;
        
        // parse data
        parse_buffer(0);
    }
    
    // parse remaining data
    parse_buffer(1);
    
    return 1;
}
